/**
 * creator:WhiteBird
 * create time:2016/10/20
 * email:zhiqiang.zhao@dhc.com.cn
 **/

#import "WhiteBirdUSPlugin.h"
#import "UMSocialUIManager.h"
#import <UMSocialCore/UMSocialCore.h>
#import <Cordova/CDV.h>
#import "TencentOpenAPI.framework/Headers/QQApiInterface.h"
#import "WXApi.h"

@implementation WhiteBirdUSPlugin{

}

- (void)pluginInitialize
{
    NSDictionary *settings = [self.commandDelegate settings];

    NSString *umengAppId = [settings objectForKey:@"wbs_umeng_appid"];
    NSLog(@"wbs_umeng_appid:%@",umengAppId);

    NSString *QQAppKey = [settings objectForKey:@"wbs_qq_appkey"];
    NSLog(@"wbs_qq_appkey:%@",QQAppKey);

    NSString *QQAppSecret = [settings objectForKey:@"wbs_qq_appsecret"];
    NSLog(@"wbs_qq_appsecret:%@",QQAppSecret);

    NSString *sinaAppKey = [settings objectForKey:@"wbs_sina_appkey"];
    NSLog(@"wbs_sina_appkey:%@",sinaAppKey);

    NSString *sinaAppSecret = [settings objectForKey:@"wbs_sina_appsecret"];
    NSLog(@"wbs_sina_appsecret:%@",sinaAppSecret);

    NSString *weChatAppKey = [settings objectForKey:@"wbs_wechat_appkey"];
    NSLog(@"wbs_weChat_appkey:%@",weChatAppKey);

    NSString *weChatAppSecret = [settings objectForKey:@"wbs_wechat_appsecret"];
    NSLog(@"wbs_weChat_appsecret:%@",weChatAppSecret);

    //打开调试日志
    [[UMSocialManager defaultManager] openLog:YES];

    //设置友盟appkey
    [[UMSocialManager defaultManager] setUmSocialAppkey:umengAppId];

    //设置新浪的appId和appKey
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_Sina appKey:sinaAppKey  appSecret:sinaAppSecret redirectURL:@"http://sns.whalecloud.com/sina2/callback"];

    //设置分享到QQ互联的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_QQ appKey:QQAppKey  appSecret:QQAppSecret redirectURL:@"http://www.PraiseTheLord.com"];

    //设置微信的appKey和appSecret
    [[UMSocialManager defaultManager] setPlaform:UMSocialPlatformType_WechatSession appKey:weChatAppKey appSecret:weChatAppSecret redirectURL:@"http://www.PraiseTheLord.com"];

    //不显示微信收藏平台（不显示某些平台的方法）
    [[UMSocialManager defaultManager] removePlatformProviderWithPlatformTypes:@[@(UMSocialPlatformType_WechatFavorite)]];

}

/*
*通过友盟官方控制面板显示分享社区
*/
- (void)share:(CDVInvokedUrlCommand*)command
{
    __weak typeof(self) weakSelf = self;
    //显示分享面板
    [UMSocialUIManager showShareMenuViewInWindowWithPlatformSelectionBlock:^(UMShareMenuSelectionView *shareSelectionView, UMSocialPlatformType platformType) {

        //调用分享方法
        [weakSelf shareWebPageToPlatformType:platformType withCommand:command];

    }];
}

/*
*分享到具体的某一平台
*/
- (void)shareToSPlatform:(CDVInvokedUrlCommand*)command
{
    if([command.arguments[4] isEqual:[NSNull null]])
    {
        [self showAlert:@"参数有误"];
    }else
    {
        if([command.arguments[4] isEqualToString:@"sina"])
        {
            [self shareWebPageToPlatformType:UMSocialPlatformType_Sina withCommand:command];
        }
        else if([command.arguments[4] isEqualToString:@"qq"])
        {
            [self shareWebPageToPlatformType:UMSocialPlatformType_QQ withCommand:command];
        }
        else if([command.arguments[4] isEqualToString:@"qzone"])
        {
            [self shareWebPageToPlatformType:UMSocialPlatformType_Qzone withCommand:command];
        }
        else if([command.arguments[4] isEqualToString:@"wx"])
        {
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatSession withCommand:command];
        }
        else if([command.arguments[4] isEqualToString:@"wxcircle"])
        {
            [self shareWebPageToPlatformType:UMSocialPlatformType_WechatTimeLine withCommand:command];
        }
        else{
            [self showAlert:@"请输入正确的平台名称"];
        }
    }

}

/*
*分享方法
*暂仅支持分享网址,其它形式分享功能待续
*/
- (void)shareWebPageToPlatformType:(UMSocialPlatformType)platformType withCommand:(CDVInvokedUrlCommand*)command
{
    NSString *title,*desc,*imageUrl,*url;

    //********** 判断传入参数是否正确
    if([command.arguments[0] isEqual:[NSNull null]] || [command.arguments[1] isEqual:[NSNull null]] || [command.arguments[2] isEqual:[NSNull null]] || [command.arguments[3] isEqual:[NSNull null]])
    {
        [self showAlert:@"参数有误"];
        return;
    }else
    {
        title = [command.arguments objectAtIndex:0];
        desc = [command.arguments objectAtIndex:1];
        imageUrl = [command.arguments objectAtIndex:2];
        url = [command.arguments objectAtIndex:3];
        NSLog(@"title:%@   desc:%@   imageUrl:%@   url:%@",title,desc,imageUrl,url);
    }

    //********** 判断平台，如果是新浪的时候使用图文分享，为其它情况的时候使用webUrl分享
    if(platformType == UMSocialPlatformType_Sina)
    {

        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];

        //判断是否安装了客户端，如果没有安装客户端只能分享文字
        NSDictionary *settings = [self.commandDelegate settings];

        NSString *sinaAppKey = [settings objectForKey:@"wbs_sina_appkey"];

        BOOL hadInstalledWeibo = [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:[@"sinaweibosso://wb" stringByAppendingString:sinaAppKey]]];

        if(hadInstalledWeibo){

            //设置文本
            messageObject.text = [[desc stringByAppendingString:@" : "] stringByAppendingString:url];

            //创建图片内容对象
            UMShareImageObject *shareObject = [[UMShareImageObject alloc] init];

            //设置分享图形
            [shareObject setShareImage:imageUrl];

            //分享消息对象设置分享内容对象
            messageObject.shareObject = shareObject;
        }
        else{
            messageObject.text = [[[desc stringByAppendingString:@" : "] stringByAppendingString:url] stringByAppendingString:@" (未安装微博平台，仅支持分享文本)"];
        }

        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
            CDVPluginResult* pluginResult = nil;
            if (error) {
                NSLog(@"************Share fail with error %@*********",error);
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"分享失败"];
            }else{
                NSLog(@"response data is %@",data);
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"分享成功"];

            }
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
        }];

    }else{
    //********** QQ Qzone 微信 朋友圈等平台
        //创建分享消息对象
        UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
        UMShareWebpageObject *shareObject = nil;
        //创建网页内容对象
        if(platformType == UMSocialPlatformType_WechatTimeLine)
        {
            NSString *context;
            //朋友圈不支持加入descr选项，所以将描述内容加入到标题中
            if([title isEqualToString:@""]&&[desc isEqualToString:@""])
            {
                context = @"";
            }
            else if(![title isEqualToString:@""]&&[desc isEqualToString:@""])
            {
                context = title;
            }
            else if(![desc isEqualToString:@""]&&[title isEqualToString:@""])
            {
                context = desc;
            }
            else
            {
                context = [[title stringByAppendingString:@" : "] stringByAppendingString:desc];
            }
            shareObject = [UMShareWebpageObject shareObjectWithTitle:context descr:desc thumImage:imageUrl];
        }
        else
        {
            shareObject = [UMShareWebpageObject shareObjectWithTitle:title descr:desc thumImage:imageUrl];
        }
        //设置网页地址
        shareObject.webpageUrl = url;

        //分享消息对象设置分享内容对象
        messageObject.shareObject = shareObject;

        //调用分享接口
        [[UMSocialManager defaultManager] shareToPlatform:platformType messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {

            CDVPluginResult* pluginResult = nil;
            if (error) {
                NSLog(@"************Share fail with error %@*********",error);
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"分享失败"];
            }else{
                NSLog(@"response data is %@",data);
                pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"分享成功"];

            }
            [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];

        }];
    }
}

/*
 * 判断是否安装QQ应用
 * 注意在ios分享中，分享到QQ空间的方法，仅与是否安装了QQ应用有关，与QQ空间应用无任何关系
 */
- (void)isInstallQQ:(CDVInvokedUrlCommand*)command
{

    CDVPluginResult* pluginResult = nil;
    if([QQApiInterface isQQInstalled]){
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"YES"];
    }else{
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"NO"];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

/*
 * 判断是否安装QQ应用
 * 注意在ios分享中，分享到QQ空间的方法，仅与是否安装了QQ应用有关，与QQ空间应用无任何关系
 */
- (void)isInstallWeChat:(CDVInvokedUrlCommand*)command
{

    CDVPluginResult* pluginResult = nil;
    if([WXApi isWXAppInstalled]){
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"YES"];
    }else{
        pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"NO"];
    }
    [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
}

/*
 * 第三方登录
 * 第三方授权获取用户信息
 */
- (void)loginByPlatform:(CDVInvokedUrlCommand*)command
{
    if([command.arguments[0] isEqual:[NSNull null]])
    {
        [self showAlert:@"参数有误"];
        return;
    }

    UMSocialPlatformType loginType = UMSocialPlatformType_UnKnown;

    if([command.arguments[0] isEqualToString:@"qq"])
    {
        loginType = UMSocialPlatformType_QQ;
    }else if([command.arguments[0] isEqualToString:@"wx"])
    {
        loginType = UMSocialPlatformType_WechatSession;
    }else if([command.arguments[0] isEqualToString:@"sina"])
    {
        loginType = UMSocialPlatformType_Sina;
    }


    [[UMSocialManager defaultManager] getUserInfoWithPlatform:loginType currentViewController:self completion:^(id result, NSError *error) {
        CDVPluginResult* pluginResult = nil;
        if (error) {

            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"授权失败"];

        } else {

            UMSocialUserInfoResponse *resp = result;

            // 授权信息
            NSLog(@"********** 授权信息 **********");
            NSLog(@"uid: %@", resp.uid);
            NSLog(@"openid: %@", resp.openid);
            NSLog(@"accessToken: %@", resp.accessToken);
            NSLog(@"expiration: %@", resp.expiration);
            NSLog(@"refreshToken: %@", resp.refreshToken);

            NSMutableDictionary *authorizeDic = [[NSMutableDictionary alloc] init];
            if(resp.uid)
            {
                [authorizeDic setValue:resp.uid forKey:@"uid"];
            }
            if(resp.openid)
            {
                [authorizeDic setValue:resp.openid forKey:@"openid"];
            }
            if(resp.accessToken)
            {
                [authorizeDic setValue:resp.accessToken forKey:@"accessToken"];
            }
            if(resp.expiration)
            {
                NSDateFormatter *forMatter = [[NSDateFormatter alloc] init];
                [forMatter setDateFormat:@"yyyy-MM-dd HH:mm:ss zzz"];
                NSString *dateStr = [forMatter stringFromDate:resp.expiration];
                [authorizeDic setValue:dateStr forKey:@"expiration"];
            }
            if(resp.refreshToken)
            {
                [authorizeDic setValue:resp.refreshToken forKey:@"refreshToken"];
            }

            // 用户信息
            NSLog(@"********** 用户信息 **********");
            NSLog(@"name: %@", resp.name);
            NSLog(@"iconurl: %@", resp.iconurl);
            NSLog(@"gender: %@", resp.gender);

            NSMutableDictionary *customDic = [[NSMutableDictionary alloc] init];
            if(resp.name)
            {
                [customDic setValue:resp.name forKey:@"name"];
            }
            if(resp.iconurl)
            {
                [customDic setValue:resp.iconurl forKey:@"iconurl"];
            }
            if(resp.gender)
            {
                [customDic setValue:resp.gender forKey:@"gender"];
            }

            NSDictionary *totalMess = @{@"authorizeDic":authorizeDic,@"customDic":customDic};

            NSLog(@"%@",totalMess);

            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsDictionary:totalMess];

        }
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];

}

/*
 * 取消授权
 */
- (void)cancelAuthorize:(CDVInvokedUrlCommand *)command
{
    if([command.arguments[0] isEqual:[NSNull null]])
    {
        [self showAlert:@"参数有误"];
        return;
    }

    UMSocialPlatformType cancelType = UMSocialPlatformType_UnKnown;

    if([command.arguments[0] isEqualToString:@"qq"])
    {
        cancelType = UMSocialPlatformType_QQ;
    }else if([command.arguments[0] isEqualToString:@"wx"])
    {
        cancelType = UMSocialPlatformType_WechatSession;
    }else if([command.arguments[0] isEqualToString:@"sina"])
    {
        cancelType = UMSocialPlatformType_Sina;
    }

    [[UMSocialManager defaultManager] cancelAuthWithPlatform:cancelType completion:^(id result, NSError *error) {
        CDVPluginResult* pluginResult = nil;
        if(error)
        {
            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_ERROR messageAsString:@"取消授权失败"];
        }else{

            pluginResult = [CDVPluginResult resultWithStatus:CDVCommandStatus_OK messageAsString:@"success"];

        }
        [self.commandDelegate sendPluginResult:pluginResult callbackId:command.callbackId];
    }];

}


//private 方法
/*
* 激活触发应用跳转结束的回调
* 功能类似相当于在AppDelegate.m 中,通过系统方法来触发回调
*/
- (void)handleOpenURL:(NSNotification *)notification
{
    NSURL* url = [notification object];
    NSString* scheme = [url scheme];
    NSLog(@"scheme:%@",scheme);

    //鉴别需要触发回调的app url scheme标识 QQ:QQ/tencent  微博:wb  微信:wx
    if([scheme hasPrefix:@"QQ"] || [scheme hasPrefix:@"tencent"] || [scheme hasPrefix:@"wb"] || [scheme hasPrefix:@"wx"] )
    {
        [[UMSocialManager defaultManager] handleOpenURL:url];
    }
}

/*
 * 提示信息
 */
- (void)showAlert:(NSString*)alertStr
{
    if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0) {
        UIAlertController *alertView = [UIAlertController alertControllerWithTitle:nil message:alertStr preferredStyle:UIAlertControllerStyleAlert];

        UIAlertAction *actionOk = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {

        }];
        [alertView addAction:actionOk];
        [self.viewController presentViewController:alertView animated:YES completion:nil];
    }
    else
    {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:nil message:alertStr delegate:self cancelButtonTitle:@"确定" otherButtonTitles: nil];
        [alert show];
    }

}
@end

